﻿using System;
using System.ComponentModel.Design;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using DataAccess;

namespace SilverlightRest.Web.Filters
{
    public class MyAuthorizeAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            // hvis vi brugte Thread.CurrentPrincipal kunne vi:

            // if (Thread.CurrentPrincipal.IsAuthenticated)
                // return;


            var authHeader = actionContext.Request.Headers.Authorization;
            if (authHeader != null)
            {
                if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(authHeader.Parameter))
                {
                    var rawCredentials = authHeader.Parameter;
                    //var encoding = Encoding.GetEncoding("iso-8859-1");
                    var encoding = Encoding.UTF8;
                    var credentials = encoding.GetString(Convert.FromBase64String(rawCredentials));
                    var split = credentials.Split(':'); // TODO: MOO do we allow : in passwords ?
                    if (split.Count() != 2)
                        throw new Exception(string.Format("Unexpected number of pieces ({0}) in credentials: {1} ", split.Count(), credentials));
                    var username = split[0];
                    var password = split[1];

                    var userRepository =
                        (IUserRepository)
                            ((Unity.WebApi.UnityDependencyResolver) GlobalConfiguration.Configuration.DependencyResolver)
                                .GetService(typeof (IUserRepository));

                    var user = userRepository.Login(username, password);
                    if (user != null)
                    {
                        // Handle adding the user to the session if applicable - then return to indicate success
                        // OR actually use what the framework already provides ?
                        // Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null); // 

                        return;
                    }
                }
            }
            HandleUnauthorized(actionContext);
        }

        private void HandleUnauthorized(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "stuff");
            //actionContext.Response.Headers.Add("WWW-Authenticate", "Basic");
        }
    }
}